from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql


app = Flask(__name__)
CORS(app)

# MySQL 连接配置
conn = pymysql.connect(host='数据库地址',
                       user='mysql用户名',
                       password='mysql密码',
                       db='数据库',
                       charset='utf8mb4',
                       cursorclass=pymysql.cursors.DictCursor)

@app.route('/messages', methods=['GET'])
def get_messages():
    with conn.cursor() as cursor:
        sql = "SELECT * FROM messages ORDER BY timestamp DESC"
        cursor.execute(sql)
        messages = cursor.fetchall()
    return jsonify(messages)

@app.route('/messages', methods=['POST'])
def post_message():
    data = request.json
    message = data.get('message')
    username = data.get('username')[:20] if data.get('username') else '匿名用户' # 截取用户名前20个字符

    if message:
        timestamp = int(time.time())  # 获取当前时间戳
        with conn.cursor() as cursor:
            sql = "INSERT INTO messages (username, content, timestamp) VALUES (%s, %s, %s)"
            cursor.execute(sql, (username, message, timestamp))
            conn.commit()
        return jsonify({'status': 'success'})
    else:
        return jsonify({'status': 'error', 'message': 'Message content is missing'})

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0',port=5000)
